package cn.edu.swu.miniwebsvr.core;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private final Config config = Config.getInstance();
    private final ExecutorService threadPool = Executors.newFixedThreadPool(10);

    public void start() {
        // TODO: [222024321072052/然娜·吐尔逊汗] 实现 ServerSocket 的创建和监听
        // 使用 try-with-resources 确保 ServerSocket 自动关闭
        try (ServerSocket serverSocket = new ServerSocket(config.getPort())) {
            System.out.println("MiniWebSvr 启动成功，监听端口：" + config.getPort());
//            System.out.println("服务器根目录: " + config.getRootDir());

            // 主服务循环
            while (true) {
                // 接受客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("接收到新的连接：" + clientSocket.getInetAddress());

                // 使用线程池处理请求
                threadPool.execute(new RequestProcessor(clientSocket));
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败或运行异常: " + e.getMessage());
            // 关闭线程池
            threadPool.shutdown();
        }
    }

    private static class RequestProcessor implements Runnable {
        private final Socket socket;

        public RequestProcessor(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            // TODO: [222024321072052/然娜·吐尔逊汗] 完善请求处理流程，确保异常安全和资源关闭
            try (Socket clientSocket = this.socket; // 确保socket关闭
                 OutputStream output = clientSocket.getOutputStream()) {

                // 1. 解析HTTP请求
                Parameter request = HttpParser.parse(clientSocket.getInputStream());
                System.out.println("处理请求: " + request.getMethod() + " " + request.getUrl());

                // 2. 路由处理
                Router router = new Router();
                router.route(request, output);

            } catch (Exception e) {
                System.err.println("请求处理异常: " + e.getMessage());
                // TODO: [222024321072052/然娜·吐尔逊汗] 可以在这里实现返回 500 错误页面的逻辑
                // 返回500错误页面
                try {
                    String errorResponse = "HTTP/1.1 500 Internal Server Error\r\n" +
                            "Content-Type: text/html\r\n" +
                            "\r\n" +
                            "<html><body><h1>500 Internal Server Error</h1>" +
                            "<p>" + e.getMessage() + "</p></body></html>";
                    socket.getOutputStream().write(errorResponse.getBytes(StandardCharsets.UTF_8));
                } catch (IOException ex) {
                    System.err.println("发送错误响应失败: " + ex.getMessage());
                }
            }
        }
    }
}